import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter/widgets.dart';
import 'package:photo_manager/photo_manager.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';

import '../../constants/extensions.dart';
import '../customs/pickers/multi_tabs_assets_picker.dart';
import 'package:wechat_assets_picker/src/internals/singleton.dart';

/// 鸿蒙平台特定的选择器方法
/// 用于解决单一媒体类型选择时相册列表加载问题
class HarmonyPickerMethods {
  
  /// 检查是否为鸿蒙平台
  static bool get isHarmonyOS {
    try {
      return Platform.isOhos;
    } catch (e) {
      return false;
    }
  }

  /// 鸭子类型检查，判断是否为多Tab选择器
  static bool _isMultiTabPicker(dynamic delegate) {
    try {
      // 检查是否存在videosProvider和imagesProvider属性
      final videosProvider = delegate.videosProvider;
      final imagesProvider = delegate.imagesProvider;
      return videosProvider != null && imagesProvider != null;
    } catch (e) {
      return false;
    }
  }
  
  /// 鸿蒙平台专用的图片选择方法
  static Future<List<AssetEntity>?> pickImagesOnHarmony(
    BuildContext context, {
    required int maxAssetsCount,
    List<AssetEntity>? selectedAssets,
  }) async {
    if (!isHarmonyOS) {
      // 非鸿蒙平台使用原来的方法
      return AssetPicker.pickAssets(
        context,
        pickerConfig: AssetPickerConfig(
          maxAssets: maxAssetsCount,
          selectedAssets: selectedAssets ?? [],
          requestType: RequestType.image,
        ),
      );
    }

    debugPrint('鸿蒙平台图片选择开始');
    // 鸿蒙平台使用image类型 + CustomFilter 只显示图片相册
    final result = await AssetPicker.pickAssets(
      context,
      pickerConfig: AssetPickerConfig(
        maxAssets: maxAssetsCount,
        selectedAssets: selectedAssets ?? [],
        requestType: RequestType.image, // 使用image类型只显示图片相册
        // 使用 CustomFilter 来精确过滤，只显示图片
        filterOptions: CustomFilter.sql(
          where: '${CustomColumns.base.mediaType} = 1', // 1 表示图片类型
          orderBy: [const OrderByItem.desc('date_modified')],
        ),
        // 添加选择预测器作为额外保障
        selectPredicate: (BuildContext context, AssetEntity asset, bool isSelected) {
          if (asset.type != AssetType.image) {
            if (context.mounted) {
              ScaffoldMessenger.of(context).showSnackBar(
                SnackBar(
                  content: Text('只能选择图片'),
                  duration: const Duration(seconds: 1),
                ),
              );
            }
            return false;
          }
          return true;
        },
      ),
    );
    debugPrint('鸿蒙平台图片选择结束');
    return result;
  }

  /// 鸿蒙平台专用的视频选择方法
  /// 使用 RequestType.video + CustomFilter 的方式来只显示视频（包括音视频）相册
  static Future<List<AssetEntity>?> pickVideosOnHarmony(
    BuildContext context, {
    required int maxAssetsCount,
    List<AssetEntity>? selectedAssets,
  }) async {
    if (!isHarmonyOS) {
      // 非鸿蒙平台使用原来的方法
      return AssetPicker.pickAssets(
        context,
        pickerConfig: AssetPickerConfig(
          maxAssets: maxAssetsCount,
          selectedAssets: selectedAssets ?? [],
          requestType: RequestType.video,
        ),
      );
    }

    debugPrint('鸿蒙平台视频选择开始');
    // 鸿蒙平台使用video类型 + CustomFilter 只显示视频相册
    final result = await AssetPicker.pickAssets(
      context,
      pickerConfig: AssetPickerConfig(
        maxAssets: maxAssetsCount,
        selectedAssets: selectedAssets ?? [],
        requestType: RequestType.video, // 使用video类型只显示视频相册
        // 使用 CustomFilter 来精确过滤，只显示视频
        filterOptions: CustomFilter.sql(
          where: '${CustomColumns.base.mediaType} IN (2, 3)', // 2 表示视频类型, 3 表示音视频类型
          orderBy: [const OrderByItem.desc('date_modified')],
        ),
        // 添加选择预测器作为额外保障
        selectPredicate: (BuildContext context, AssetEntity asset, bool isSelected) {
          if (asset.type != AssetType.video && asset.type != AssetType.audio) {
            if (context.mounted) {
              ScaffoldMessenger.of(context).showSnackBar(
                SnackBar(
                  content: Text('只能选择视频或音频'),
                  duration: const Duration(seconds: 1),
                ),
              );
            }
            return false;
          }
          return true;
        },
      ),
    );
    debugPrint('鸿蒙平台视频选择结束');
    return result;
  }

  /// 鸿蒙平台专用的自定义过滤条件方法
  static Future<List<AssetEntity>?> pickAssetsWithCustomFilterOnHarmony(
    BuildContext context, {
    required int maxAssetsCount,
    List<AssetEntity>? selectedAssets,
    RequestType requestType = RequestType.video,
    FilterOptionGroup? filterOptions,
  }) async {
    if (!isHarmonyOS) {
      // 非鸿蒙平台使用原来的方法
      return AssetPicker.pickAssets(
        context,
        pickerConfig: AssetPickerConfig(
          maxAssets: maxAssetsCount,
          selectedAssets: selectedAssets ?? [],
          requestType: requestType,
          filterOptions: filterOptions,
        ),
      );
    }

    // 鸿蒙平台使用对应的类型 + CustomFilter
    return AssetPicker.pickAssets(
      context,
      pickerConfig: AssetPickerConfig(
        maxAssets: maxAssetsCount,
        selectedAssets: selectedAssets ?? [],
        requestType: requestType, // 使用对应的类型只显示相应相册
        filterOptions: filterOptions,
      ),
    );
  }

  /// 鸿蒙平台专用的保持滚动位置方法
  static Future<List<AssetEntity>?> pickAssetsWithKeepScrollOffsetOnHarmony({
    required BuildContext context,
    required DefaultAssetPickerBuilderDelegate Function() delegate,
    List<AssetEntity>? selectedAssets,
  }) async {
    if (!isHarmonyOS) {
      // 非鸿蒙平台使用原来的方法
      return AssetPicker.pickAssetsWithDelegate(
        context,
        delegate: delegate(),
      );
    }

    try {
      // 检查delegate函数返回值是否为null，如果是则创建一个新的实例
      final delegateInstance = delegate() ?? DefaultAssetPickerBuilderDelegate(
        provider: DefaultAssetPickerProvider(),
        initialPermission: PermissionState.authorized,
        keepScrollOffset: true,
      );
      
      // 确保在鸿蒙平台上正确处理滚动位置，添加更完善的空值检查
      if (delegateInstance.keepScrollOffset) {
        // 记录当前滚动位置（如果存在）
        if (Singleton.scrollPosition != null) {
          debugPrint('当前保存的滚动位置: ${Singleton.scrollPosition?.pixels}');
        } else {
          debugPrint('当前没有保存的滚动位置');
        }
        
        // 在下一帧恢复滚动位置，添加更多空值检查和边界检查
        WidgetsBinding.instance.addPostFrameCallback((_) {
          try {
            if (delegateInstance.gridScrollController.hasClients) {
              final scrollPosition = Singleton.scrollPosition;
              if (scrollPosition != null) {
                final pixels = scrollPosition.pixels;
                // 确保滚动位置在有效范围内
                final maxScrollExtent = delegateInstance.gridScrollController.position.maxScrollExtent;
                final minScrollExtent = delegateInstance.gridScrollController.position.minScrollExtent;
                final targetPixels = pixels.clamp(minScrollExtent, maxScrollExtent);
                
                debugPrint('恢复滚动位置到: $targetPixels (原值: $pixels, 范围: $minScrollExtent - $maxScrollExtent)');
                delegateInstance.gridScrollController.jumpTo(targetPixels);
              } else {
                debugPrint('滚动位置为空');
              }
            } else {
              debugPrint('滚动控制器没有客户端');
            }
          } catch (e, stackTrace) {
            debugPrint('恢复滚动位置时出错: $e');
            debugPrint('错误堆栈: $stackTrace');
          }
        });
      }
      
      // 鸿蒙平台保持滚动位置功能，添加错误处理
      return await AssetPicker.pickAssetsWithDelegate(
        context,
        delegate: delegateInstance,
      );
    } catch (e, stackTrace) {
      debugPrint('鸿蒙平台保持滚动位置功能错误: $e');
      debugPrint('错误堆栈: $stackTrace');
      
      // 显示错误提示
      if (context.mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('保持滚动位置功能暂时不可用: ${e.toString()}'),
            duration: const Duration(seconds: 2),
          ),
        );
      }
      
      return selectedAssets;
    }
  }

  /// 鸿蒙平台专用的多Tab选择器方法
  /// 解决多Tab选择器在鸿蒙平台上转圈不加载的问题
  static Future<List<AssetEntity>?> pickAssetsWithMultiTabOnHarmony({
    required BuildContext context,
    required DefaultAssetPickerBuilderDelegate Function() delegate,
    List<AssetEntity>? selectedAssets,
  }) async {
    if (!isHarmonyOS) {
      // 非鸿蒙平台使用原来的方法
      return AssetPicker.pickAssetsWithDelegate(
        context,
        delegate: delegate(),
      );
    }

    try {
      final delegateInstance = delegate();
      
      // 鸿蒙平台多Tab选择器功能，确保所有Provider都已正确初始化
      if (delegateInstance is MultiTabAssetPickerBuilder) {
        // 确保所有Tab的Provider都已初始化并获取路径数据
        final multiTabDelegate = delegateInstance;
        
        // 初始化完成后延迟一段时间确保数据加载
        await Future.delayed(const Duration(milliseconds: 200));
        
        // 确保主Provider已获取路径
        if (multiTabDelegate.provider.paths.isEmpty) {
          debugPrint('鸿蒙平台多Tab选择器：初始化主Provider路径数据');
          await multiTabDelegate.provider.getPaths();
        }
        
        // 确保视频Provider已获取路径
        if (multiTabDelegate.videosProvider.paths.isEmpty) {
          debugPrint('鸿蒙平台多Tab选择器：初始化视频Provider路径数据');
          await multiTabDelegate.videosProvider.getPaths();
        }
        
        // 确保图片Provider已获取路径
        if (multiTabDelegate.imagesProvider.paths.isEmpty) {
          debugPrint('鸿蒙平台多Tab选择器：初始化图片Provider路径数据');
          await multiTabDelegate.imagesProvider.getPaths();
        }
        
        debugPrint('鸿蒙平台多Tab选择器：所有Provider路径数据加载完成');
      }
      
      // 鸿蒙平台多Tab选择器功能
      return await AssetPicker.pickAssetsWithDelegate(
        context,
        delegate: delegateInstance,
      );
    } catch (e, stackTrace) {
      debugPrint('鸿蒙平台多Tab选择器功能错误: $e');
      debugPrint('错误堆栈: $stackTrace');
      
      // 显示错误提示
      if (context.mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('多Tab选择器功能暂时不可用: ${e.toString()}'),
            duration: const Duration(seconds: 2),
          ),
        );
      }
      
      return selectedAssets;
    }
  }

  /// 鸿蒙平台预览功能增强
  /// 添加额外的错误处理和重试机制
  static Future<List<AssetEntity>?> pushToViewerOnHarmony(
    BuildContext context, {
    int currentIndex = 0,
    required List<AssetEntity> previewAssets,
    required ThemeData themeData,
    DefaultAssetPickerProvider? selectorProvider,
    ThumbnailSize? previewThumbnailSize,
    List<AssetEntity>? selectedAssets,
    SpecialPickerType? specialPickerType,
    int? maxAssets,
    bool shouldReversePreview = false,
    AssetSelectPredicate<AssetEntity>? selectPredicate,
    bool shouldAutoplayPreview = false,
    bool useRootNavigator = false,
    RouteSettings? pageRouteSettings,
  }) async {
    if (!isHarmonyOS) {
      // 非鸿蒙平台使用原来的方法
      return AssetPickerViewer.pushToViewer(
        context,
        currentIndex: currentIndex,
        previewAssets: previewAssets,
        themeData: themeData,
        selectorProvider: selectorProvider,
        previewThumbnailSize: previewThumbnailSize,
        selectedAssets: selectedAssets,
        specialPickerType: specialPickerType,
        maxAssets: maxAssets,
        shouldReversePreview: shouldReversePreview,
        selectPredicate: selectPredicate,
        shouldAutoplayPreview: shouldAutoplayPreview,
        useRootNavigator: useRootNavigator,
        pageRouteSettings: pageRouteSettings,
      );
    }

    try {
      // 记录预览资源信息
      debugPrint('预览资源数量: ${previewAssets.length}');
      debugPrint('当前索引: $currentIndex');
      
      // 检查预览资源是否为空
      if (previewAssets.isEmpty) {
        debugPrint('鸿蒙平台预览功能错误: 预览资源为空');
        // 显示错误提示
        if (context.mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(
              content: Text('预览功能暂时不可用: 没有可预览的资源'),
              duration: Duration(seconds: 2),
            ),
          );
        }
        return selectedAssets;
      }
      
      // 检查当前索引是否有效
      if (currentIndex < 0 || currentIndex >= previewAssets.length) {
        debugPrint('当前索引无效，重置为0');
        currentIndex = 0;
      }
      
      final ThumbnailSize? effectivePreviewThumbnailSize = previewThumbnailSize;

      debugPrint('使用缩略图大小: ${effectivePreviewThumbnailSize?.width}x${effectivePreviewThumbnailSize?.height}');

      // 鸿蒙平台预览功能，添加错误处理
      return await AssetPickerViewer.pushToViewer(
        context,
        currentIndex: currentIndex,
        previewAssets: previewAssets,
        themeData: themeData,
        selectorProvider: selectorProvider,
        previewThumbnailSize: effectivePreviewThumbnailSize,
        selectedAssets: selectedAssets,
        specialPickerType: specialPickerType,
        maxAssets: maxAssets,
        shouldReversePreview: shouldReversePreview,
        selectPredicate: selectPredicate,
        shouldAutoplayPreview: shouldAutoplayPreview,
        useRootNavigator: useRootNavigator,
        pageRouteSettings: pageRouteSettings,
      );
    } catch (e, stackTrace) {
      debugPrint('鸿蒙平台预览功能错误: $e');
      debugPrint('错误堆栈: $stackTrace');
      
      // 显示错误提示
      if (context.mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('预览功能暂时不可用: ${e.toString()}'),
            duration: const Duration(seconds: 2),
          ),
        );
      }
      
      return selectedAssets;
    }
  }
}